package com.example.web03homework.Controller;

import com.example.web03homework.pojo.Book;
import com.example.web03homework.pojo.Category;
import com.example.web03homework.service.BookService;
import com.example.web03homework.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {
    //借助service对象，操作数据库
    @Autowired
    private BookService bookService;
    
    @Autowired
    private CategoryService categoryService;

    // 任务1：查询指定图书
    @RequestMapping(value ="/{id}", method = RequestMethod.GET)
    public Book getById(@PathVariable Integer id) {
        return bookService.getById(id);
    }
    
    // 任务2：按条件查询图书信息，条件有关键字、分类
    @RequestMapping(value ="/search", method = RequestMethod.GET)
    public List<Book> getByCondition(@RequestParam(required = false) String keyword, 
                                     @RequestParam(required = false) Integer categoryId) {
        return bookService.getByCondition(keyword, categoryId);
    }
    
    // 任务3：新增图书，请求方式POST
    @RequestMapping(value = "",method = RequestMethod.POST)
    public ResponseEntity<String> insert(@RequestBody Book book) {
        bookService.addBook(book);
        return ResponseEntity.ok("新增成功");
    }
    
    // 任务4：修改图书信息，请求方式PUT
    @RequestMapping(value = "",method = RequestMethod.PUT)
    public ResponseEntity<String> update(@RequestBody Book book) {
        bookService.updateBook(book);
        return ResponseEntity.ok("修改成功");
    }
    
    // 任务5：修改图书状态信息
    @RequestMapping(value = "/{id}/{status}", method = RequestMethod.PUT)
    public ResponseEntity<String> updateStatus(@PathVariable Integer id, @PathVariable Integer status) {
        bookService.modifyBookStatus(id, status);
        return ResponseEntity.ok("状态修改成功");
    }
    
    // 任务6：删除指定图书
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<String> deleteById(@PathVariable Integer id) {
        bookService.deleteById(id);
        return ResponseEntity.ok("删除成功");
    }
    
    // 任务7：批量删除图书，请求方式DELETE
    @RequestMapping(value = "/batch",method = RequestMethod.DELETE)
    public ResponseEntity<String> deleteByIds(@RequestBody List<Integer> ids) {
        bookService.removeBatchByIds(ids);
        return ResponseEntity.ok("批量删除成功");
    }
    
    // 任务8：查询出所有一级分类（含二级分类）
    @RequestMapping(value = "/categories", method = RequestMethod.GET)
    public List<Category> getAllCategories() {
        return categoryService.getAllCategories();
    }
}

